package br.com.wuo.genericInventary.application;

import java.io.IOException;

import com.thingmagic.ReadListener;
import com.thingmagic.Reader;
import com.thingmagic.ReaderException;
import com.thingmagic.TagReadData;

public class ShelfReader {
	
	private Reader reader;
	private boolean connected = false;
	private String connectionString;
	
	public ShelfReader(String port) {
		
		connectionString = "eapi:///" + port;
		System.out.println("Connection string: " + connectionString);		
	}
	
	public void connect() throws IOException {
        try {
            reader = Reader.create(connectionString);
            System.out.println("Reader criado");
            reader.connect();
            connected = true;
            System.out.println("Reader conectado");
            
            if (Reader.Region. UNSPEC == (Reader.Region) reader.paramGet("/reader/region/id")) {
                reader.paramSet("/reader/region/id", Reader.Region.NA);
            }
            
        } catch (Exception e) {
            System.out.println("Couldn't connect: " + e.getStackTrace());
        }
    }
	

	public void disconnect() throws IOException {
        connected = false;
		reader.destroy();
    }
	
	public boolean isConnected() {
        return connected;
    }


    public void startReading() throws IOException {
        reader.startReading();
    }


    public void stopReading() throws IOException {
        reader.stopReading();
    }
    
    public TagReadData[] read(long miliseconds) throws ReaderException{
    	return reader.read(miliseconds);
    }
    
    
    public void setPower(int power) throws IOException {
        try {
            reader.paramSet("/reader/radio/readPower", power);
        } catch (ReaderException ex) {
            System.out.println("Set Power: " + ex.getStackTrace());
        }
    }
    
    public String getPower() throws IOException {
        String power = "";
        try {
            power = reader.paramGet("/reader/radio/readPower").toString();
        } catch (ReaderException ex) {
        	System.out.println("Get Power: " + ex.getStackTrace());
        }
        return power;
    }
    
    public void addReadListener(ReadListener rl){
    	
    	reader.addReadListener(rl);
    	
    }

}
